package com.cola.programmer.interceptor.admin;

import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Grup:com.cola.programmer.interceptor
 * @Auther:cola
 * @Data:2021/5/20-2021-05-23:33
 * @version:1.0
 * 后台登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        Object admin = request.getSession().getAttribute("admin");
        if (admin==null){
            //表示未登录或者登录失效
            System.out.println("连接"+requestURI+"进入拦截器!");
            String header = request.getHeader("X-Requested-With");
            //判断ajax请求
            if ("XMLHttpRequest".equals(header)){
                //表示ajax请求
                Map<String,String> ret=new HashMap<String, String>();
                ret.put("type","error");
                ret.put("msg","登录会话超时货还未登录,请重新登录!!");
                response.getWriter().write(JSONObject.fromObject(ret).toString());
            }
            //表示是普通连接跳转,直接重定向道登录页面
            response.sendRedirect(request.getServletContext().getContextPath()+"/system/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
